package config

import (
	"github.com/Unknwon/goconfig"
	"fmt"
	"os"
)


//readMySQLConf 读取Mysql数据库配置文件
func ReadMySQLConf(configPath string) (dbURL string, err error) {
	host := ""
	port := "0"
	user := ""
	password := ""
	schema := ""
	//获取当前文件夹执行路径
	workDir, err := os.Getwd()
	if err == nil {

		configFilePath := workDir + configPath
		confHandler, err := goconfig.LoadConfigFile(configFilePath)
		if err == nil {
			//取MYSQL数据库信息
			mode := "mysql"

			if hostTemp, err := confHandler.GetValue(mode, "host"); err == nil {
				host = hostTemp
			}
			if portTemp, err := confHandler.GetValue(mode, "port"); err == nil {
				port = portTemp
			}
			if userTemp, err := confHandler.GetValue(mode, "user"); err == nil {
				user = userTemp
			}
			if passTemp, err := confHandler.GetValue(mode, "password"); err == nil {
				password = passTemp
			}
			if sechemTemp, err := confHandler.GetValue(mode, "schema"); err == nil {
				schema = sechemTemp
			}

			return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, password, host, port, schema), nil
		}
		return "", err
	}
	return "", err
}


//readServerConf 读取Server的配置信息
func ReadServerConf(configPath string) (listenHost string, err error) {
	host := ""
	port := "8080"

	//获取当前文件夹执行路径
	workDir, err := os.Getwd()
	if err == nil {

		configFilePath := workDir + configPath
		confHandler, err := goconfig.LoadConfigFile(configFilePath)
		if err == nil {
			//取MYSQL数据库信息
			mode := "server"

			if hostTemp, err := confHandler.GetValue(mode, "host"); err == nil {
				host = hostTemp
			}
			if portTemp, err := confHandler.GetValue(mode, "port"); err == nil {
				port = portTemp
			}

			return fmt.Sprintf("%s:%s", host, port), nil
		}
		return "", err
	}
	return "", err
}